package com.cytech.cloudclinic.moudle.main.drug.add2.dosage;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.adapter.AddDrugTagMulAdapter;
import com.cytech.cloudclinic.base.BaseFragment;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.event.RefreshDrug;
import com.cytech.cloudclinic.bean.event.UpdateAddTagEvent;
import com.cytech.cloudclinic.bean.req.AddDrugReq;
import com.cytech.cloudclinic.bean.resp.RespDrugDetail;
import com.cytech.cloudclinic.dialog.AddDrugTagDialog;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.yechaoa.yutils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.cytech.cloudclinic.app.Constant.DRUG_TAG_2;
import static com.cytech.cloudclinic.app.Constant.MODE_FREQUENCY_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_MIN_PACKAGE_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_PACKAGE_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_TAG_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_USER_METHOD_ID;

public class AddDrugDosageFragment2 extends BaseFragment<AddDrugDosagePresenter2> implements AddDrugDosageView2 {
    @BindView(R.id.rv_add_drug_tag)
    RecyclerView recyclerView;
    @BindView(R.id.rv_add_drug_use)
    RecyclerView rvUse;
    @BindView(R.id.rv_add_drug_frequency)
    RecyclerView rvFrequency;
    @BindView(R.id.rv_add_drug_default_value)
    RecyclerView rvDefaultValue;

    @BindView(R.id.add_drug_tag_default_value)
    EditText defaultValueEt;

    private int drugTagId;
    private int drugId;
    private int parentDrugTagId;
    private List<AddDrugTag> userList;
    private List<AddDrugTag> frequencyList;
    private List<AddDrugTag> defaultValueList;

    private AddDrugTagAdapter mUseAdapter;
    private AddDrugTagAdapter mFrequencyAdapter;
    private AddDrugTagAdapter mDefaultValueAdapter;

    private AddDrugTagDialog addTagDrugDialog;

    private AddDrugReq drug;

    private List<AddDrugTag> mList;
    //药品标签适配器
    private AddDrugTagMulAdapter mAdapter;

    public static AddDrugDosageFragment2 newInstance(int drugTagId, int drugId, int parentDrugTagId) {
        AddDrugDosageFragment2 fragment = new AddDrugDosageFragment2();
        //如果有参数，使用Bundle传递
        Bundle bundle = new Bundle();
        bundle.putInt("drugTagId", drugTagId);
        bundle.putInt("drugId", drugId);
        bundle.putInt("parentDrugTagId", parentDrugTagId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected AddDrugDosagePresenter2 createPresenter() {
        return new AddDrugDosagePresenter2(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_add_drug_dosage2;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {
        drugTagId = getArguments().getInt("drugTagId");
        drugId = getArguments().getInt("drugId");
        parentDrugTagId = getArguments().getInt("parentDrugTagId");
        drug = (AddDrugReq) getArguments().getSerializable("addDrugReq");

        initUseRv();
        iniFrequencyRv();
        initDefaultValueRv();
        initTagRv();

        presenter.getSummaryList(MODE_USER_METHOD_ID, parentDrugTagId);

    }

    @Override
    public void getUseSuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        mUseAdapter.setNewInstance(data);
        presenter.getSummaryList(MODE_FREQUENCY_ID, parentDrugTagId);
    }

    @Override
    public void getFrequencySuccess(List<AddDrugTag> data) {
        //获取标签
        presenter.getSummaryList(MODE_TAG_ID, parentDrugTagId);
        data.add(new AddDrugTag(true));
        mFrequencyAdapter.setNewInstance(data);

    }

    @Override
    public void getDrugTagSuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        mAdapter.setNewInstance(data);
        if (drugId != 0) {
            presenter.getDrugDetail(drugId);
        }
    }

    @Override
    public void getDrugDetailSuccess(RespDrugDetail drugDetail) {
        //用法
        String usage_mode = drugDetail.usage_mode;
        if(usage_mode!=null){
            List<AddDrugTag> useList = mUseAdapter.getData();
            for (int i = 0; i < useList.size(); i++) {
                if (usage_mode.equals(useList.get(i).value)) {
                    mUseAdapter.setCurrentPos(i);
                    break;

                }
            }
        }

        //频次
        String frequency = drugDetail.frequency;
        if(frequency!=null){
            List<AddDrugTag> frequencyList = mFrequencyAdapter.getData();
            for (int i = 0; i < frequencyList.size(); i++) {
                if (frequency.equals(frequencyList.get(i).value)) {
                    mFrequencyAdapter.setCurrentPos(i);
                    break;
                }
            }
            defaultValueEt.setText(String.valueOf(drugDetail.dosage));
        }

        //标签
        List<String> selectTag = drugDetail.label_ids;
        List<AddDrugTag> allTag = mAdapter.getData();
        Log.d("TAG", "getDrugDetailSuccess: "+allTag.size());
        for(int i=0;i<allTag.size();i++){
            for(int j=0;j<selectTag.size();j++){
                if(selectTag.get(j).equals(allTag.get(i).value)){
                    mAdapter.getItem(i).isSelect = true;
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    //标签
    public void initTagRv(){
        mList = new ArrayList<>();
        mAdapter = new AddDrugTagMulAdapter(R.layout.item_add_drug_tag,mList);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),5));
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if(mAdapter.getItem(position).isAddData){
                    addTagDrugDialog = new AddDrugTagDialog(MODE_TAG_ID,parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(),"rvPackage");
                }else{
                    mAdapter.getItem(position).isSelect = !mAdapter.getItem(position).isSelect;
                    mAdapter.notifyItemChanged(position);
                }
            }
        });

        mAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if(!mAdapter.getItem(position).isAddData){
                    presenter.delSummaryTag(mAdapter.getItem(position).id);
                    mAdapter.remove(position);
                }
                return false;
            }
        });
    }

    //用法
    public void initUseRv() {
        userList = new ArrayList<>();
        mUseAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, userList);
        rvUse.setLayoutManager(new GridLayoutManager(getActivity(), 6));
        rvUse.setAdapter(mUseAdapter);
        mUseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mUseAdapter.getItem(position).isAddData) {
                    addTagDrugDialog = new AddDrugTagDialog(MODE_USER_METHOD_ID, parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(), "rvUse");
                } else {
                    mUseAdapter.setCurrentPos(position);
                }
            }
        });

        mUseAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (!mUseAdapter.getItem(position).isAddData) {
                    presenter.delSummaryTag(mUseAdapter.getItem(position).id);
                    mUseAdapter.remove(position);
                }
                return false;
            }
        });
    }

    //频次
    public void iniFrequencyRv() {
        frequencyList = new ArrayList<>();
        mFrequencyAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, frequencyList);
        rvFrequency.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        rvFrequency.setAdapter(mFrequencyAdapter);
        mFrequencyAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mFrequencyAdapter.getItem(position).isAddData) {
                    addTagDrugDialog = new AddDrugTagDialog(MODE_FREQUENCY_ID, parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(), "rvUse");
                } else {
                    mFrequencyAdapter.setCurrentPos(position);
                }
            }
        });

        mFrequencyAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (!mFrequencyAdapter.getItem(position).isAddData) {
                    presenter.delSummaryTag(mFrequencyAdapter.getItem(position).id);
                    mFrequencyAdapter.remove(position);
                }
                return false;
            }
        });
    }

    public void initDefaultValueRv() {
        defaultValueList = presenter.buildNumValue();
        mDefaultValueAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, defaultValueList);
        rvDefaultValue.setLayoutManager(new GridLayoutManager(getActivity(), 6));
        rvDefaultValue.setAdapter(mDefaultValueAdapter);
        mDefaultValueAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = mDefaultValueAdapter.getItem(position).value;
                defaultValueEt.setText(presenter.getRealNumValue(value, defaultValueEt.getText().toString()));
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateData(UpdateAddTagEvent event) {
        presenter.getSummaryList(event.mode, parentDrugTagId);
    }

    @OnClick(R.id.btn_add_drug_save)
    public void save(View v) {
        if (drug == null) {
            ToastUtil.showToast("请填写基本信息点击下一步");
            return;
        }

        drug.drug_id = drugId;
        drug.usage_mode = mUseAdapter.getSelectName();
        drug.frequency = mFrequencyAdapter.getSelectName();
        drug.dosage = ConvertUtils.toDouble(defaultValueEt.getText().toString());
        drug.label_ids = getTagNameList();
        presenter.addDrug(drug);
    }

    @Override
    public void addDrugSuccess() {
        EventBus.getDefault().post(new RefreshDrug());
        ToastUtil.showToast("成功");
        getActivity().finish();
    }

    //获取选中的药品标签
    public List<String> getTagNameList(){
        List<String> tagNameList = new ArrayList<>();
        List<AddDrugTag> tags =  mAdapter.getData();
        for(AddDrugTag tag: tags){
            if(tag.isSelect){
                tagNameList.add(tag.value);
            }
        }
        return tagNameList;
    }
}
